<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="商品类别" prop="categoryId">
        <el-select v-model="queryParams.categoryId" filterable placeholder="请选择商品类别" style="">
          <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.categoryName"
            :value="item.id"
            :disabled="item.categoryStatus == 0 ? true : false"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="捐赠来源" prop="sourceId">
        <el-select v-model="queryParams.sourceId" filterable placeholder="请选择捐赠来源" style="">
          <el-option
            v-for="item in donate_option"
            :key="item.id"
            :label="item.donateName"
            :value="item.id"
            @keyup.enter.native="handleQuery"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['supermarket:product:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['supermarket:product:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['supermarket:product:remove']"
        >删除
        </el-button>
      </el-col>

      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['supermarket:product:export']"-->
      <!--        >导出-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column type="index" width="50"></el-table-column>
      <!--      <el-table-column label="商品id" align="center" prop="id"/>-->
      <el-table-column label="商品名称" align="center" prop="productName"/>
      <el-table-column label="商品图片" align="center" prop="indexImg">
        <template slot-scope="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.indexImg"
            fit="fit"
          ></el-image>
        </template>
      </el-table-column>
      <!--      <el-table-column label="捐赠来源" align="center" prop="donationSource">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span v-if="scope.row.sourceCategory==1">{{ scope.row.donationSource }}(个人)</span>-->
      <!--          <span v-if="scope.row.sourceCategory==2">{{ scope.row.donationSource }}(公司)</span>-->
      <!--          <span v-if="scope.row.sourceCategory==3">{{ scope.row.donationSource }}(组织)</span>-->
      <!--          <span v-if="scope.row.sourceCategory==4">{{ scope.row.donationSource }}(政府)</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->

      <el-table-column label="积分价值" align="center" prop="integratedWorth"/>
      <el-table-column label="商品类别" align="center" prop="categoryName"></el-table-column>
      <el-table-column label="总库存" align="center" prop="inventory"/>
      <!--      <el-table-column label="上架时间" align="center" prop="releaseTime" width="180">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span>{{ scope.row.releaseTime }}</span>-->
      <!--          &lt;!&ndash;          <span>{{ parseTime(scope.row.releaseTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>&ndash;&gt;-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="商品状态" align="center" prop="productStatus">
        <template slot-scope="scope">
          <span v-if="scope.row.productStatus==0">待上架</span>
          <span v-else-if="scope.row.productStatus==1">上架</span>
          <span v-else>下架</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['supermarket:product:edit']"
          >修改
          </el-button>
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-document"-->
          <!--            @click="handleDetail(scope.row)"-->
          <!--          >详情-->
          <!--          </el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['supermarket:product:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改超市商品管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="850px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <div class="flex-row">
          <el-form-item label="商品图片" prop="indexImg" style="width: 48%;margin-right: 30px">
            <el-upload
              class="avatar-uploader"
              action
              :http-request="selectPicUpload"
              :show-file-list="false"
            >
              <img v-if="form.indexImg" :src="form.indexImg" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <div v-if="form.id!=null">
            <el-form-item label="总库存:" prop="inventory">
              <div>{{ form.inventory }}</div>
            </el-form-item>
            <el-form-item label="销售量:" prop="salesVolume">
              <div>{{ form.salesVolume }}</div>
            </el-form-item>
            <el-form-item label="积分价值:" prop="integratedWorth">
              <div>{{ form.integratedWorth }}</div>
            </el-form-item>
          </div>
        </div>

        <div class="flex-row">
          <el-form-item label="商品名称" prop="productName" style="width: 48%;margin-right: 30px">
            <el-input v-model="form.productName" placeholder="请输入商品名称"/>
          </el-form-item>
          <!--          <el-form-item label="积分价值" prop="integratedWorth">-->
          <!--            <el-input v-model="form.integratedWorth" placeholder="请输入积分价值"/>-->
          <!--          </el-form-item>-->
        </div>
        <div class="flex-row">
          <el-form-item label="捐赠来源" prop="donateSourceDTOS" style="width: 48%;margin-right: 30px">
            <el-select
              v-model="form.donateSourceDTOS"
              multiple
              filterable
              allow-create
              default-first-option
              value-key="id"
              placeholder="请选择捐赠来源"
            >
              <el-option
                v-for="item in donate_option"
                :key="item.id"
                :label="item.donateName"
                :value="{ id: item.id }"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="商品类别" prop="categoryId">
            <el-select v-model="form.categoryId" filterable placeholder="请选择商品类别" style=""
                       @change="categoryChange"
            >
              <el-option
                v-for="item in categoryList"
                :key="item.id"
                :label="item.categoryName"
                :value="item.id"
                :disabled="item.categoryStatus == 0 ? true : false"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div>

        <!--        <div class="flex-row">-->
        <!--                    <el-form-item label="商品品牌" prop="brand" style="width: 48%;margin-right: 30px">-->
        <!--                      <el-input v-model="form.brand" placeholder="请输入品牌"/>-->
        <!--                    </el-form-item>-->
        <!--          <el-form-item label="保质期" prop="sellByDate">-->
        <!--            <el-date-picker clearable-->
        <!--                            v-model="form.sellByDate"-->
        <!--                            value-format="yyyy-MM-dd"-->
        <!--                            placeholder="请选择保质期到期时间"-->
        <!--            >-->
        <!--            </el-date-picker>-->
        <!--          </el-form-item>-->
        <!--        </div>-->

        <!--        <div class="flex-row">-->
        <!--          <el-form-item label="商品风格" prop="style" style="width: 48%;margin-right: 30px">-->
        <!--            <el-input v-model="form.style" placeholder="请输入商品风格"/>-->
        <!--          </el-form-item>-->
        <!--          <el-form-item label="商品功能" prop="functionality">-->
        <!--            <el-input v-model="form.functionality" placeholder="请输入商品功能性"/>-->
        <!--          </el-form-item>-->
        <!--        </div>-->
        <div class="flex-row">
          <el-form-item label="是否上架" prop="productStatus" style="width: 48%;margin-right: 30px">
            <el-radio-group v-model="form.productStatus">
              <el-radio label="0">待上架</el-radio>
              <el-radio label="1">上架</el-radio>
              <el-radio label="2">下架</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="上架时间" prop="releaseTime" v-if="form.productStatus==0"
                        :rules="[{required: true, message: '请选择上架时间', trigger: 'change'}]"
          >
            <el-date-picker clearable
                            v-model="form.releaseTime"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="请选择上架时间"
            >
            </el-date-picker>
          </el-form-item>
        </div>
        <el-form-item label="商品介绍" prop="serviceIntroduce">
          <el-input v-model="form.serviceIntroduce" type="textarea" :autosize="true" placeholder="请输入商品介绍"/>
        </el-form-item>
        <el-form-item label="图片介绍" prop="imgUrl">
          <el-upload
            action
            class="avatar-uploader"
            :http-request="selectPicListUpload"
            list-type="picture-card"
            :file-list="fileList"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
          >
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" class="avatar">
          </el-dialog>
        </el-form-item>
        <div class="flex-row">
          <el-form-item label="兑换地点" prop="locationId" style="width: 48%;margin-right: 30px">
            <el-select v-model="form.locationId" filterable placeholder="请选择兑换地点" style="">
              <el-option
                v-for="item in location_option"
                :key="item.id"
                :label="item.exchangeLocation"
                :value="item.id"
                :disabled="item.locationStatus == 0 ? true : false"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="保质期" prop="sellByDate">
            <el-date-picker clearable
                            v-model="form.sellByDate"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择保质期到期时间"
            >
            </el-date-picker>
          </el-form-item>
        </div>

        <!--        商品选项-->
        <div class="text-bold" style="margin: 20px 0; font-size: medium">商品选项</div>

        <div v-if="open"
             :style="{'overflow-y': (form.inventories.length > 3 ? 'auto' : ''), height: (form.inventories.length > 3 ? '550px' : ''),padding: '0 20px 0 0'}"
        >
          <div v-for="(inventories,index) in form.inventories" :key="index">
            <div class="flex-row-bt" style="margin: 20px 0">
              <div class="text-bold" style=" color: #409EFF">选项{{ index + 1 }}</div>
              <!--          删除选项-->
              <el-button type="danger" icon="el-icon-delete" size="mini" circle @click="deleteSelect(index)"
              ></el-button>
            </div>

            <el-form-item label="商品编码" prop="inventories.proCode">
              <el-input v-model="inventories.proCode" placeholder="请输入商品编码"/>
            </el-form-item>

            <!--          服务-->
            <div v-if="form.kind==2" class="flex-row" style="width: auto;">
              <el-form-item label="使用日期" :prop="'inventories.' + index + '.timeInterval'"
                            :rules="[{required: true, message: '请选择使用日期', trigger: 'change'}]"
                            style="width: 43%"
              >
                <el-date-picker
                  style="width: 300px"
                  v-model="inventories.timeInterval"
                  type="daterange"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="时间段" :prop="'inventories.' + index + '.timeSlot'"
                            style="width: 52%;margin-left: 30px"

              >
                <div class="flex-row">
                  <el-time-select
                    placeholder="起始时间"
                    v-model="selectTime[index].startTime"
                    :picker-options="{start: '07:00', step: '00:30',end: '24:00'}"
                  >
                  </el-time-select>
                  <div style="margin: 0 10px;">-</div>
                  <el-time-select
                    placeholder="结束时间"
                    v-model="selectTime[index].endTime"
                    :picker-options="{start: '07:00', step: '00:30',end: '24:00',minTime: selectTime[index].startTime}"
                  >
                  </el-time-select>
                </div>
              </el-form-item>
            </div>
            <!--          物品-->
            <div class="flex-row" v-else>
              <el-form-item label="颜色" prop="inventories.color">
                <el-input v-model="inventories.color" placeholder="请输入颜色"/>
              </el-form-item>
              <el-form-item label="尺码" prop="inventories.size">
                <el-input v-model="inventories.size" placeholder="请输入尺码"/>
              </el-form-item>
              <el-form-item label="规格" prop="inventories.specifications">
                <el-input v-model="inventories.specifications" placeholder="请输入规格"/>
              </el-form-item>
            </div>

            <div class="flex-row">
              <el-form-item label="积分价值" :prop="'inventories.' + index + '.integratedWorth'"
                            :rules="[{required: true, message: '请输入商品选项积分价值', trigger: 'change'}]"
                            style="width: 48%;margin-right: 30px;"
              >
                <el-input v-model="inventories.integratedWorth" placeholder="请输入积分价值"/>
              </el-form-item>
              <el-form-item label="库存" :prop="'inventories.' + index + '.inventory'"
                            :rules="[{required: true, message: '请输入商品选项库存', trigger: 'change'}]"
              >
                <el-input-number v-model="inventories.inventory" size="medium" :min="0" label="请输入库存"
                ></el-input-number>
              </el-form-item>
            </div>

          </div>

        </div>

        <el-button type="primary" size="small" plain @click="addSelect" style="margin-top: 10px">增加选项</el-button>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import {
  listProduct,
  getProduct,
  delProduct,
  addProduct,
  updateProduct,
  uploadPic,
  deleteInventory
} from '@/api/supermarket/product'
import {imgUrl} from '@/utils/request'
import {getNameAndId} from '@/api/supermarket/category'
import {donateList} from '@/api/donate/source'
import {getLocationAndId} from '@/api/supermarket/location'

export default {
  name: 'Product',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 超市商品管理表格数据
      productList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        categoryId: null,
        sourceId: null,
        productStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productName: [
          {required: true, message: '请输入商品名称', trigger: 'change'},
        ],
        indexImg: [
          {required: true, message: '请上传商品图片', trigger: 'change'}
        ],
        sourceCategory: [
          {required: true, message: '请选择捐赠类别', trigger: 'change'}
        ],
        categoryId: [
          {required: true, message: '请选择商品类别', trigger: 'change'}
        ],
        productStatus: [
          {required: true, message: '请选择是否上架', trigger: 'change'}
        ],
        // integratedWorth: [
        //   {required: true, message: '请输入积分价值', trigger: 'change'}
        // ],
        donateSourceDTOS: [
          {type: 'array', required: true, message: '请选择捐赠来源', trigger: 'change'}
        ],
        locationId: [
          {required: true, message: '请输入兑换地点', trigger: 'change'},
        ],
        donationSource: [
          {required: true, message: '请输入捐赠来源', trigger: 'change'}
        ],
        imgUrl: [
          {type: 'array', required: true, message: '请上传商品介绍图片', trigger: 'change'}
        ],
        inventories: [
          {type: 'array', required: true, message: '请添加商品选择', trigger: 'change'}
        ],
      },
      type_options: [{
        value: null,
        label: '全部'
      }, {
        value: 0,
        label: '物品'
      }, {
        value: 1,
        label: '服务'
      }],
      //图片拼接头
      imgUrl: imgUrl,

      //商品介绍图片上传
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],

      //时间段
      selectTime: [],

      //商品分类类表
      categoryList: [],
      //捐赠来源list
      donate_option: [],
      // 兑换地点list
      location_option: [],
    }
  },
  created() {
    this.getList()
    //请求商品分类
    this.getCategoryList()
    //获取捐赠来源list
    this.getDonateList()
    //请求兑换地点list
    this.getLocationList()
  },
  methods: {
    //商品类别切换
    categoryChange() {
      this.categoryList.filter(item => {
          if (item.id == this.form.categoryId) {
            this.form.kind = item.kind
          }
        }
      )
    },
    //请求兑换地点list
    getLocationList() {
      getLocationAndId().then(res => {
        this.location_option = res
      });
    },
    //请求商品分类
    getCategoryList() {
      getNameAndId().then(res => {

        this.categoryList = res
      });
    },
    //获取捐赠来源list
    getDonateList() {
      donateList().then(response => {
        this.donate_option = response
      })
    },
    //上传商品图片
    selectPicUpload(obj) {
      let fd = new FormData() //参数的格式是formData格式的
      fd.append('file', obj.file) //参数
      uploadPic(fd, { modularName: 'SUPERMARKET' }).then(res => {
        this.form.indexImg = res
      })
    },
    // beforeAvatarUpload(file) {
    //   const isJPG = file.type === 'image/jpeg/png/jpg';
    //   const isLt2M = file.size / 1024 / 1024 < 2;
    //
    //   if (!isJPG) {
    //     this.$message.error('上传头像图片只能是 JPG 格式!');
    //   }
    //   if (!isLt2M) {
    //     this.$message.error('上传头像图片大小不能超过 2MB!');
    //   }
    //   return isJPG && isLt2M;
    // },
    //商品介绍图片
    selectPicListUpload(obj) {
      console.log(obj)
      let fd = new FormData() //参数的格式是formData格式的
      fd.append('file', obj.file) //参数
      console.log(fd)
      uploadPic(fd, { modularName: 'SUPERMARKET' }).then(res => {
        this.form.cover = res
      })
    },
    //移除图片
    handleRemove(file, fileList) {
      console.log(file, fileList);
      //拿到删除索引
      let index = this.fileList.indexOf(file)
      this.form.imgUrl.splice(index, 1)
      const list = JSON.parse(JSON.stringify(fileList))
      this.fileList = list.map(item => ({
        name: item.name,
        url: item.url
      }))
    },
    //图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //增加商品选项
    addSelect() {
      this.form.inventories.push({
        "color": null,
        "size": null,
        "inventory": null,
        "timeSlot": null,
        "specifications": null,
        "timeInterval": null,
        "integratedWorth": null,
        proCode: null
      })
      //时间段
      this.selectTime.push({
        startTime: null,
        endTime: null
      })
    },
    //删除商品选项
    deleteSelect(index) {
      this.$modal.confirm('是否确认删除此商品选项?').then(function () {
      }).then(() => {
        if (this.form.inventories[index].id) {
          deleteInventory(this.form.inventories[index].id).then(response => {
            if (response.code === 200) {
              this.form.inventories.splice(index, 1)
              //如果是服务类型，删掉时间段
              if (this.form.kind == 2) {
                this.selectTime.splice(index, 1)
              }
              this.$modal.msgSuccess('删除成功')
            } else {
              this.$modal.msgError(response.msg)
            }
          })
        } else {
          this.form.inventories.splice(index, 1)
          //如果是服务类型，删掉时间段
          if (this.form.kind == 2) {
            this.selectTime.splice(index, 1)
          }
          this.$modal.msgSuccess('删除成功')
        }
      }).catch(() => {
      });
    },
    //时间段切换
    changeTime() {
      for (let i = 0; i < this.form.inventories.length; i++) {
        if (this.selectTime[i].startTime == null || this.selectTime[i].endTime == null) {
          // this.$modal.msgError("请选择商品使用时间段");
        } else {
          this.form.inventories[i].timeSlot = this.selectTime[i].startTime + '-' + this.selectTime[i].endTime
        }
      }
    },
    /** 查询超市商品管理列表 */
    getList() {
      this.loading = true
      listProduct(this.queryParams).then(response => {
        this.productList = response.pageData
        this.total =parseInt(response.total)
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        indexImg: null,
        productName: null,
        integratedWorth: null,
        categoryId: null,
        categoryName: null,
        sellByDate: null,
        salesVolume: null,
        inventory: null,
        releaseTime: null,
        productStatus: '1',
        detailsId: null,
        exchangeLocation: null,
        donationSource: null,
        donateSourceDTOS: [],
        brand: null,
        style: null,
        functionality: null,
        serviceIntroduce: null,
        imgUrl: [],
        inventories: [],
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        area: null,
        kind: '1'
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      //商品详情图
      this.fileList = []
      //时间段
      this.selectTime = []
      this.title = '添加商品'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.fileList = []
      //时间段
      this.selectTime = []
      const id = row.id || this.ids
      getProduct(id).then(response => {
        this.form = response
        if (this.form.kind == '2'){
          this.form.inventories =  this.form.inventories.map(item => {
            if (item.timeInterval != null){
              return {
                ...item,
                timeInterval: [item.timeInterval.slice(0,10),item.timeInterval.slice(11,21)]
              }
            }else {
              return {
                ...item
              }
            }
          })
        }
        for (let i = 0; i < this.form.imgUrl.length; i++) {
          this.fileList.push({
            name: 'image', url:this.form.imgUrl[i]
          })
        }
        if (this.form.kind == 2) {
          for (let i = 0; i < this.form.inventories.length; i++) {
            if (this.form.inventories[i].timeSlot != null){
              this.selectTime.push({
                startTime: this.form.inventories[i].timeSlot.split('-')[0],
                endTime: this.form.inventories[i].timeSlot.split('-')[1]
              })
            }else {
              this.selectTime.push({
                startTime:null,
                endTime:null
              })
            }

          }
        }
        this.open = true
        this.title = '修改商品'
      })
    },
    /** 提交按钮 */
    submitForm() {
      console.log('111212121')
      console.log(this.form.inventories)
      if (this.form.inventories.length == 0 || this.form.inventories == null) {
        this.$modal.msgError("请添加商品选项");
      } else {
        if (this.form.kind == 2) {
          if (this.selectTime.startTime != undefined && this.selectTime.endTime != undefined){
            this.form.inventories =  this.form.inventories.map(item => {
              return {
                ...item,
                timeInterval: item.timeInterval[0] + '-' + item.timeInterval[1],
                timeSlot:this.selectTime.startTime + '-' + this.selectTime.endTime
              }
            })
          }else {
            console.error('1212')
            this.form.inventories =  this.form.inventories.map(item => {
              return {
                ...item,
                timeInterval: item.timeInterval[0] + '-' + item.timeInterval[1],
                timeSlot:""
              }
            })
          }
          this.changeTime()
        }
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateProduct(this.form).then(response => {
                this.$modal.msgSuccess('修改成功')
                this.open = false
                this.getList()
              })
            } else {
              addProduct(this.form).then(response => {
                this.$modal.msgSuccess('新增成功')
                this.open = false
                this.getList()
              })
            }
          }
        })

      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除该商品？').then(function () {
        return delProduct(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('supermarket/product/export', {
        ...this.queryParams
      }, `product_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
